package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"practice-hub/cache"
	"practice-hub/model"
	"strconv"
	"time"
)

func AddPerSon(c *gin.Context) {
	per_son_code := c.PostForm("per_son_code")
	per_son_name := c.PostForm("per_son_name")
	per_son_phone := c.PostForm("per_son_phone")
	person := model.PerSon{
		PerSonCode:  per_son_code,
		PerSonName:  per_son_name,
		PerSonPhone: per_son_phone,
	}
	err := model.DB.Create(&person).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
	return
}
func AddPerSonOrder(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_from := c.PostForm("order_from")
	order_to := c.PostForm("order_to")
	pid, _ := strconv.Atoi(c.PostForm("pid"))
	order := model.PerSonOrder{
		OrderCode: order_code,
		OrderFrom: order_from,
		OrderTo:   order_to,
		Pid:       pid,
	}
	err := model.DB.Create(&order).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
	return
}
func PerSonOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var perSon []model.PerSonOrderList
	redis_key := "person_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("per_son_orders").
			Select("per_son_orders.id AS OrderId",
				"order_code AS OrderCode",
				"order_from AS OrderFrom",
				"order_to AS OrderTo",
				"per_son_code AS PerSonCode",
				"per_son_name AS PerSonName",
				"per_son_phone as PerSonPhone").
			Joins("LEFT JOIN per_sons ON per_sons.id = per_son_orders.pid").
			Offset(offset).Limit(size).Debug().Find(&perSon)
		jsonData, _ := json.Marshal(perSon)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &perSon)
	}
	var total int64
	model.DB.Model(&model.PerSonOrder{}).Count(&total)
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": perSon})
	return
}
